<template>
  <div>
    <FixedOperation>
      <el-row>
        <el-col :span="10" :offset="14" class="flex justify-end">
          <slot></slot>
          <el-button
            type="primary"
            plain
            @click="handleSave"
            v-if="isNew || isFirst"
            >保存</el-button
          >
          <el-button
            type="primary"
            plain
            @click="process"
            v-if="isNew || notInitiated"
          >
            发起申请</el-button
          >
          <el-button
            type="primary"
            plain
            @click="viewProcess"
            v-if="isEdit && isApprove"
          >
            查看流程</el-button
          >
          <el-button type="primary" plain @click="handleBack"> 返回</el-button>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="templatePage app-container">
      <el-form id="temForm" :rules="rules" ref="from" :model="form">
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="文档用途："
              style="width: 100%"
              label-width="180px"
              prop="fileUse"
            >
              <el-input v-model="form.fileUse"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="文件类型："
              style="width: 100%"
              label-width="180px"
              prop="fileAttribute"
            >
              {{ form.fileAttribute }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="文件清单："
              style="width: 100%"
              label-width="180px"
              prop="fileName"
            >
              <div>
                <el-button
                  type="primary"
                  @click="changeFiles"
                  :disabled="!isNew && isApprove"
                  >文件选择</el-button
                >
                <span class="ml-5px text-13px text-gray-400"
                  >最多选择不超过10个</span
                >
                <div
                  class="mt-5px"
                  v-for="(item, index) in fileList"
                  :key="index"
                >
                  <svg-icon
                    :icon-class="getSvgName(form.fileType)"
                    class="w-18px h-18px align-middle"
                  ></svg-icon>
                  {{ item }}
                  <el-button plain text @click="download(index)" v-if="isPass"
                    >下载</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="文件状态："
              style="width: 100%"
              label-width="180px"
              prop="fileStatus"
            >
              {{ form.fileStatus }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4" style="flex-wrap: wrap">
            <el-form-item
              label="申请时间："
              style="width: 100%"
              label-width="180px"
              prop="time"
            >
              {{ form.time }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="width: 100%">
          <el-col :span="18" :offset="4">
            <el-form-item
              label="申请人："
              style="width: 100%"
              label-width="180px"
              prop="applicantName"
            >
              {{ form.applicantName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="申请部门："
              label-width="180px"
              style="width: 100%"
              prop="deptName"
            >
              {{ form.deptName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="申请单位："
              label-width="180px"
              style="width: 100%"
              prop="orgName"
            >
              {{ form.orgName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="详细说明："
              label-width="180px"
              style="width: 100%"
              prop="remark"
            >
              <el-input
                type="textarea"
                placeholder="输入文件用途说明"
                :rows="5"
                maxlength="100"
                show-word-limit
                v-model="form.remark"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <submission-process
        :dialogParam="dialogParam"
        :flowOptions="flowOptions"
        @initiate="handleClose('initiate')"
        @close="handleClose('examine')"
      />
      <el-dialog
        v-model="showChangeBox"
        title="文件选择"
        :close-on-click-modal="false"
        align-center
        @close="closeChangeBox"
        class="fileChangeDialog"
      >
        <div class="flex">
          <el-input
            placeholder="请输入文件名"
            class="w-6/12 mb-10px mr-15px"
            v-model="keywords"
          ></el-input>
          <el-button type="primary" @click="queryFile">搜索</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button @click="pathBack" v-if="isIntoFolder">后退</el-button>
        </div>
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @row-dblclick="intoFloder"
          id="fileTable"
          row-key="fileId"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="fileName" label="文件名称" min-width="300">
            <template #default="scope">
              <div v-if="scope.row.isDir === '1'">
                <i class="i-fluent-emoji-file-folder"></i>
                <span class="ml-5px">{{ scope.row.origFileName }}</span>
              </div>
              <div v-else>
                <i class="iconfont icon-wenjian"></i>
                <span class="ml-5px">{{ scope.row.origFileName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="fileType" label="类型" width="120" />
          <el-table-column prop="fileSize" label="文件大小" width="120" />
          <el-table-column prop="openStatus" label="公开状态" width="150">
            <template #default="scope">
              <div>
                {{ open_state[scope.row.openStatus].label }}
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="updateTime" label="修改时间" width="200" /> -->
          <!-- <el-table-column prop="createBy" label="上传人员" width="150" /> -->
        </el-table>
        <pagination
          v-show="fileListPage.total > 0"
          :total="fileListPage.total"
          v-model:page="fileListPage.pageNum"
          v-model:limit="fileListPage.pageSize"
          @pagination="pageChange"
        />
        <template #footer>
          <div>
            <el-button @click="closeChangeBox">取消</el-button>
            <el-button type="primary" @click="confirmDialog"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="downloadApprove">
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { getDept } from '@/api/system/dept'
import { open_state } from '@/hooks/dict/contract.js'
import { format } from 'date-fns'
import { getCurrentInstance, nextTick } from 'vue'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'
import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  fileApplyAdd,
  fileApplyGet,
  fileApplyUpdate,
  getFileListPage,
  searchFiles
} from '@/api/fileManage'
import { downloadFile } from '@/utils/request'

const { proxy } = getCurrentInstance()
const userData = useUserStore()
const route = useRoute()
const router = useRouter()
const isNew = ref(!!location.href.match(/downloadApprove/))
const isEdit = ref(!!location.href.match(/editApprove/))
const data = reactive({
  form: {},
  rules: {
    fileUse: [{ required: true, message: '请输入文件用途', trigger: 'blur' }],
    applicantName: [{ required: true }],
    fileName: [{ required: true, message: '请选择文件', trigger: 'blur' }],
    fileAttribute: [{ required: true }],
    fileStatus: [{ required: true }],
    time: [{ required: true }],
    deptName: [{ required: true }],
    orgName: [{ required: true }]
    // remark: [{ required: true, message: '请输入用途说明', trigger: 'blur' }]
  },
  dialogParam: {},
  tableData: [],
  fileListPage: {
    fileId: '',
    pageNum: 1,
    pageSize: 10,
    total: 0,
    recursive: false
  },
  fileList: [],
  filePathList: [],
  filterList: []
})

const {
  form,
  dialogParam,
  rules,
  tableData,
  fileListPage,
  fileList,
  filePathList,
  filterList
} = toRefs(data)
const projectId = ref('')
const proInsId = ref('')
const isCanStart = ref(true)
const flowOptions = ref([]) //该业务的流程数据
const isSave = ref(false) //是否保存成功，保存后才可以审批
const isExamine = ref(true) //是否可以审批(办理详情 访问的时候不能审批，编辑页面 改业务已经发起审批了就不能审批)
const proId = ref('')
const fileIdList = ref([])

defineExpose({
  handleSave
})

const isIntoFolder = computed(() => {
  return fileIdList.value.length !== 1
})
const initFlowFn = async type => {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({ pageNum: 1, pageSize: 9999, category: type })
  flowOptions.value = comRes.rows
  // 2.根据
  if (!flowOptions.value || JSON.stringify(flowOptions.value) == '[]') {
    console.log('未建流程')
    //2.1 没有流程-提示不能新建数据
    proxy.$modal.msgError('该业务没有流程，不能新建')
    handleBack()
  } else if (flowOptions.value.length == 1) {
    console.log('1条流程')
    //2.2 流程只有一个，只有一条流程时，则不弹出框流程提交审核按钮隐藏，直接点击保存
    isExamine.value = false
  } else {
    //2.3多条流程时
  }
}
const props = defineProps({
  id: {
    type: String,
    default: ''
  }
})

const isPass = ref(false) // 是否通过审批
const origFileName = ref('')
const isApprove = ref(false) // 是否发起审批
const isFirst = ref(false) //是否第一环节
const notInitiated = ref(true)
async function init() {
  // 文件管理跳转带参数 --文件信息
  // 申请资料审批跳转带参数 -- 文件id 流程id
  const id = route.query.id ? route.query.id : props.id
  if (id) {
    const nodeData = await getNodeData(id)
    isFirst.value = nodeData.data === null || nodeData.data.isFirst === 'Y'
    notInitiated.value =
      !nodeData.data || nodeData.data.nowTaskName === '流程未发起'
    fileApplyGet({ id }).then(res => {
      form.value = res.data
      form.value.time = format(
        new Date(form.value.createTime),
        'yyyy-MM-dd hh:mm:ss'
      )
      fileList.value = form.value.fileName.split(',')
      filePathList.value = form.value.filePath.split(',')
      isPass.value = res.data.checkStatus === '05'
      isApprove.value = !!res.data.proInsId
    })
  } else {
    const fileData = JSON.parse(decodeURI(route.query.file))
    const dept = await getDept(userData.userInfo.deptId)
    const org = await getDept(userData.userInfo.orgId)
    if (fileData) {
      form.value = {
        applicant: userData.userInfo.userId,
        applicantName: userData.userInfo.nickName,
        fileName: fileData.origFileName,
        fileType: fileData.fileType,
        fileStatus: ref(open_state).value[fileData.openStatus].label,
        time: format(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        deptName: dept.data.deptName,
        deptId: dept.data.deptId,
        orgId: org.data.deptId,
        orgName: org.data.deptName,
        remark: '',
        fileAttribute: fileData.fileAttribute,
        filePath: fileData.url ? fileData.url : fileData.fileId,
        fileParent: fileData.directoryId
      }
      fileList.value = form.value.fileName.split(',')
      filePathList.value = form.value.filePath.split(',')
    }
  }
  fileIdList.value.push(form.value.fileParent)
}

// 保存
async function handleSave() {
  // if (fileList.value.length === 0) {
  //   proxy.$modal.msgWarning('请选择文件')
  //   return
  // }
  return new Promise((resolve, reject) => {
    form.value.fileName = fileList.value.toString()
    form.value.filePath = filePathList.value.toString()
    proxy.$refs['from'].validate(async valid => {
      if (valid) {
        if (isNew.value && !isSave.value) {
          const fileId = await fileApplyAdd(form.value)
          if (fileId.code === 200) {
            proxy.$modal.msgSuccess('保存成功')
            proId.value = fileId.msg
            isSave.value = true
            resolve(fileId.msg)
            // if (!isExamine.value && !!location.href.match(/downloadApprove/)) {
            //   process()
            // }
          } else {
            reject(fileId.msg)
          }
        } else {
          // form.value.fileName = fileList.value.toString()
          // form.value.filePath = filePathList.value.toString()
          const file = await fileApplyUpdate(form.value)
          if (file.code === 200) {
            const id = route.query.id || proId.value
            resolve(id)
            proxy.$modal.msgSuccess('更新成功')
          } else {
            reject(file.msg)
          }
        }
      }
    })
  })
}

// 审批
async function process() {
  let id
  try {
    id = await handleSave()
    if (id) {
      dialogParam.value.visible = true
      dialogParam.value.businessId = id
      dialogParam.value.businessName = '文件下载审批'
      dialogParam.value.categoryCode = '11'
    }
  } catch (error) {
    console.log(error)
  }
}

const getBusinessProStatusFn = async () => {
  let statusRes = await getBusinessProStatus({ businessId: projectId.value })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    isCanStart.value = true
    initFlowFn(11) //业务类型==>流程分类 页面查看
  } else {
    isCanStart.value = false
  }
}

// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      dialogParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功-关闭当前路由
      dialogParam.value.visible = false
      handleBack()
      break
  }
}
// 返回handleBack
const handleBack = () => {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
}

function viewProcess() {
  router.push({
    path: '/process/workDetail',
    query: {
      procInsId: proInsId.value,
      //   taskId: row.taskId,
      processed: false
    }
  })
}

watch(
  () => props.id,
  val => {
    if (location.href.match(/editApprove/)) {
      console.log('editApprove')
      //编辑页面---------------
      projectId.value = val || route.query.id
      proInsId.value = route.query.proInsId
      dialogParam.value.businessId = val
      // init()
      isSave.value = true
      //根据业务查询审批状态
      getBusinessProStatusFn()
    } else if (
      (val && !!location.href.match(/detail/)) ||
      (val && !!location.href.match(/workDetail/))
    ) {
      console.log('detail or workDetail')
      // 待办详情-访问--------------------
      projectId.value = val
      dialogParam.value.businessId = val
      // init()
      isSave.value = true
      isCanStart.value = false
    } else if (location.href.match(/downloadApprove/)) {
      console.log('downloadApprove')
      // 新建页面 ---------------
      // 走业务流程
      initFlowFn(11)
      isExamine.value = true
      // init()
    }
  },
  {
    immediate: true
  }
)

function download(index) {
  if (!form.value.fileAttribute === '合同范本') {
    downloadFile(filePathList.value[index], fileList.value[index])
  } else {
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = filePathList.value[index]
    link.download = fileList.value[index]
    document.body.appendChild(link)
    link.click()
    link.remove()
  }
}

const showChangeBox = ref(false)
// 选择文件
async function changeFiles() {
  showChangeBox.value = true
  pageChange()
}

// 关闭弹窗
function closeChangeBox() {
  showChangeBox.value = false
  keywords.value = ''
  fileIdList.value = [form.value.fileParent]
  fileListPage.value.pageNum = 1
  fileListPage.value.pageSize = 10
}

// 弹窗确定事件
function confirmDialog() {
  // const fList = []
  // const pathList = [...filePathList.value]
  // filterList.value.forEach((v, i) => {
  //   if (pathList.indexOf(v.filePath) < 0) {
  //     pathList.push(v.filePath)
  //     fList.push(v.origFileName)
  //   }
  // })
  filePathList.value = filterList.value.map(v => v.filePath)
  fileList.value = filterList.value.map(v => v.origFileName)
  if (fileList.value.length > 10) {
    proxy.$modal.msgWarning('文件最多可选择10个')
    return
  }
  // filePathList.value = [...pathList]
  // fileList.value = [...fileList.value, ...fList]
  closeChangeBox()
}

// 请求列表
async function pageChange(id) {
  fileListPage.value.fileId = id || form.value.fileParent
  const fData = await getFileListPage(fileListPage.value)
  if (fData.code === 200 && fData.data) {
    tableData.value = fData.data.records
    fileListPage.value.total = fData.data.total
    if (fileList.value.length) {
      nextTick(() => {
        tableData.value.forEach(v => {
          if (
            filePathList.value.indexOf(v.url) > -1 ||
            filePathList.value.indexOf(v.fileId) > -1
          ) {
            proxy.$refs.multipleTableRef.toggleRowSelection(v, true)
          }
        })
      })
    }
  }
}

// 弹窗列表选择
function handleSelectionChange(val) {
  console.log(val, '123')
  const isDir = val.filter(v => v.isDir === '1')
  if (isDir.length) {
    proxy.$modal.msgWarning('当前不可选择文件夹')
    nextTick(() => {
      proxy.$refs.multipleTableRef.toggleRowSelection(isDir[0], false)
    })
    return
  }
  const filter = []
  val.forEach(v => {
    filter.push({
      fileName: v.fileName,
      origFileName: v.origFileName,
      filePath: form.value.fileAttribute === '合同范本' ? v.url : v.fileId
    })
  })
  filterList.value = filter
}

const keywords = ref('')
function queryFile() {
  if (keywords.value) {
    searchFiles({
      searchCode: keywords.value,
      pathName: form.value.fileAttribute
    }).then(res => {
      if (res.code === 200) {
        tableData.value = [...res.data.folder, ...res.data.file]
        fileListPage.value.total = 0
      }
    })
  } else {
    reset()
  }
}

function reset() {
  fileListPage.value.pageNum = 1
  fileListPage.value.pageSize = 10
  fileIdList.value = [form.value.fileParent]
  pageChange()
  keywords.value = ''
}

// 进入文件夹
async function intoFloder(row, cloumn, event) {
  if (row.isDir !== '1') {
    // 不是文件夹
    return
  }
  fileListPage.value.pageNum = 1
  fileListPage.value.pageSize = 10
  console.log(row)
  pageChange(row.fileId)
  fileIdList.value.push(row.fileId)
}

function pathBack() {
  // if (fileIdList.value) {

  // }
  fileIdList.value.pop()
  const { length } = fileIdList.value
  pageChange(fileIdList.value[length - 1])
}
// 设置svgs
function getSvgName(type) {
  type = type.replace('文件', '')
  let fileType = 'file_'
  if (type.includes('doc')) {
    return fileType + 'word'
  }
  if (type.includes('pdf')) {
    return fileType + 'pdf'
  }
  if ('rar, zip, gz, bz2'.match(type)) {
    return fileType + 'rar'
  }
  if (type.includes('xls')) {
    return fileType + 'excel'
  }
  if (type.includes('ppt')) {
    return fileType + 'ppt'
  }
  if (type.includes('txt')) {
    return fileType + 'notepad'
  }
  if ('bmp, gif, jpg, jpeg, png'.match(type)) {
    return fileType + 'img'
  }
  if ('mp4, avi, rmvb'.match(type)) {
    return fileType + 'video'
  }
  return fileType + 'icon'
}
init()
</script>

<style scoped lang="scss">
.clickDownLoad {
  color: rgba(255, 0, 0, 0.5);
  display: inline-block;
  margin-left: 15px;
  cursor: pointer;
}
// .fileChangeDialog {
:deep(.fileChangeDialog .el-dialog__body) {
  height: 600px;
  position: relative;
  overflow: hidden;
}
:deep(.fileChangeDialog #fileTable) {
  height: calc(100% - 90px);
  overflow-y: auto;
}
// }

:deep(.pagination-container) {
  position: absolute;
  bottom: 20px;
  right: 0;
}
</style>
